package chapter02.problem02;

import chapter02.utils.SinglyListNode;

public class Problem02 {

	@SuppressWarnings("unchecked")
	public static <T> SinglyListNode<T> constructSinglyList(int size) {
		SinglyListNode<Integer> head = new SinglyListNode<Integer>(1, null);
		SinglyListNode<Integer> current = head;

		for (int i = 0; i < size; ++i) {
			SinglyListNode<Integer> node = new SinglyListNode<>(i);
			current.setNext(node);
			current = node;

		}
		return (SinglyListNode<T>) head;
	}

	public static <T> String printList(SinglyListNode<T> head) {
		SinglyListNode<T> current = head;
		if (head == null)
			return "[]";
		StringBuilder builder = new StringBuilder("[ ");
		while (current != null) {
			builder.append(current.getItem() + ", ");
			current = current.getNext();
		}
		builder.append("]");
		return builder.toString();
	}

	public static <T> SinglyListNode<T> deleteAtIndex(SinglyListNode<T> head, int index) {
		SinglyListNode<T> current = head;
		if (head == null) {
			throw new NullPointerException("Head is null!");
		}
		int size = 0;
		if (index <= 0) {
			System.out.println("请输入正确的index");
			throw new IndexOutOfBoundsException("index: " + index);
		}
		while (current != null) {
			current = current.getNext();
			size++;
		}
		current = head;
		if (index > size)
			throw new IndexOutOfBoundsException("Size: " + size + " Index: "
					+ index);
		if (index == size) {
			head = head.getNext();
			return head;
		}
		while (size > index + 1) {
			current = current.getNext();
			size--;
		}
		current.setNext(current.getNext().getNext());
		return head;
	}

	public static void main(String[] args) {
		SinglyListNode<Object> head1 = Problem02.constructSinglyList(10);
		System.out.println("Before delete: " + Problem02.printList(head1));
		head1 = Problem02.deleteAtIndex(head1, 11);
		System.out.println("After delete: " + Problem02.printList(head1));
	}
}
